<template>
  <n-modal
    :show="window_open ?? false"
    :on-mask-click="window_off"
    :draggable="cfg.drag"
    :auto-focus="false"
    :class="`${main_class} ${removeclass == true ? `` : `modal_gtbox model_v2`}`"
    to=".v1_body"
    :style="`width: ${wd ?? 800}px`"
    size="huge"
  >
    <template #default="{ draggableClass }">
      <div class="v2win">
        <div class="modal_gttitle" :class="draggableClass" v-if="cfg.mobile == false">
          <div class="_x" @click="window_off">X</div>
          {{ title }}
        </div>
        <template v-else>
          <div class="modal_mbtitle">
            <div class="_x" @click="window_off">X</div>
            {{ title }}
          </div>

          <div style="margin-top: 5px"></div>
        </template>

        <div class="model_box">
          <div style="width: 100%"><slot></slot><slot name="content"></slot></div>
        </div>
        <div class="mb_modal_ft" v-if="cfg.mobile == true"></div>
        <div class="modal_gtend">
          <n-flex>
            <slot name="footer"></slot>
            <n-button type="gt_w" :size="cfg.sizebtn" @click="window_off">{{
              offsub_title ?? "关闭"
            }}</n-button>
            <n-button
              type="gt_y"
              v-if="upsub == true"
              :size="cfg.sizebtn"
              @click="$emit('upsub_fun')"
              >{{ upsub_title ?? "提交" }}</n-button
            >
          </n-flex>
        </div>
      </div>
    </template>
  </n-modal>
</template>
<script>
import { cfg } from "@/cfg/cfg.js";
import { v4 as uuidv4 } from "uuid";

export default {
  props: {
    window_open: Boolean,
    removeclass: Boolean,
    title: String,
    wd: String,
    main_class: String,
    upsub: Boolean,
    offsub_title: String,
    upsub_title: String,
    upsub_fun: Function,
  },
  setup(props, { emit }) {
    const rdid = uuidv4();
    const window_off = () => {
      emit("update:window_open", false);
    };

    const hand = (event) => {
      if (props.window_open == true) {
        let back = event.state.forward;
        let modal = back.replace(/.*modal=/, "")?.split("&")[0];
        if (modal == rdid) {
          emit("update:window_open", false);
        }
      }
    };

    watch(
      () => props.window_open,
      (newVal) => {
        if (newVal == true) {
          cfg.router.push({
            query: {
              ...cfg.route.query,
              modal: rdid,
            },
          });
        } else {
          if (cfg.route.query.modal == rdid) {
            cfg.router.back();
          }
        }
      }
    );

    onUnmounted(() => {
      window.removeEventListener("popstate", hand);
    });
    onMounted(async () => {
      window.addEventListener("popstate", hand);
      return;
    });

    return { window_off, cfg };
  },
};
</script>
